package com.yfq.springframework.beans.support;

import com.sun.istack.internal.Nullable;
import com.yfq.springframework.beans.BeansException;
import com.yfq.springframework.beans.FactoryBean;
import com.yfq.springframework.beans.config.BeanDefinition;
import com.yfq.springframework.beans.config.BeanPostProcessor;
import com.yfq.springframework.beans.factory.ConfigurableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 姚凤桥
 * @date 2023/1/8 17:06
 * @description
 */
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    /**
     * BeanPostProcessors to apply in createBean
     */
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    @Override
    public Object getBean(String beanName) {
        return getBean(beanName, new Object[]{});
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getBean(String beanName, Class<T> clazz) {
        return (T) getBean(beanName);
    }

    @Override
    public Object getBean(String beanName, Object... args) {
        return doGetBean(beanName,null,args,false);
    }

    @SuppressWarnings("unchecked")
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
                              @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
        Object singleton = getSingletonBean(name);

        if (singleton != null) {
            return (T) getObjectForBeanInstance(singleton, name);
        }

        BeanDefinition beanDefinition = getBeanDefinition(name);

        Object bean = createBean(name, beanDefinition, args);

        return (T) getObjectForBeanInstance(bean, name);
    }

    private Object getObjectForBeanInstance(Object beanInstance, String beanName) {
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        //如果获取的bean是一个FactoryBean，那么就需要调用这个FactoryBean的getObject方法来返回对象
        Object object = getCachedObjectForFactoryBean(beanName);

        if (object == null) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }

        return object;
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName);

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object... args);

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return beanPostProcessors;
    }
}
